﻿IF EXISTS (
    SELECT
      1
    FROM sysobjects
    WHERE id = OBJECT_ID('bd_proc_leave_cancel_lactation')
      AND type IN ('P', 'PC')
  )
  DROP PROCEDURE bd_proc_leave_cancel_lactation

GO

-- =============================================
-- Author:      YFC
-- Create date: 2020-08-15 20:49:04
-- Database:    [scm_main-hysj2]
-- Description: 请假管理-取消授乳假
-- =============================================

CREATE PROCEDURE bd_proc_leave_cancel_lactation
  @JsonData VARCHAR(MAX)
AS
BEGIN
  SET NOCOUNT ON;

  SELECT *
  INTO #data
  FROM OPENJSON(@JsonData)
  WITH (
    user_serial INT
    , leave_type_id VARCHAR(200) 
    , leave_type_name VARCHAR(200)
    , leave_hours INT
    , leave_status INT
    , leave_date DATETIME
    , leave_bill_id INT
  )

  DECLARE @total INT, @i INT, @orderId BIGINT, @userSerial BIGINT, @applyDate DATE, @htType INT, @hours INT, @json VARCHAR(MAX)

  SELECT @total = COUNT(1), @i = 0 FROM #data 


  BEGIN TRY
  	BEGIN TRANSACTION
  		
      WHILE @i < @total 
      BEGIN  
      	
        SELECT TOP 1 @orderId = leave_bill_id, @userSerial = user_serial, @applyDate = leave_date, @hours = leave_hours FROM #data 
    
        --更新请假状态为无效
        UPDATE lr_kqingj SET whether_validity = 0 WHERE order_id = @orderId AND user_serial = @userSerial AND kssj = @applyDate
    
        IF NOT EXISTS(
        	SELECT 1
        	FROM lr_kqingj WHERE ISNULL(whether_validity, 0) = 1
        ) 
        BEGIN
          --如果请假单明细全部已经取消，则取消整个请假单
          UPDATE bd_leave_order SET is_del = 1 WHERE order_id = @orderId
        END
        
    
        --返还授乳假
        SELECT @json = (
           SELECT @orderId orderId, @userSerial userSerial, GETDATE() applyDate, @hours deduct_usage FROM #data 
           FOR JSON AUTO
         )
 
    
        EXEC bd_proc_vacation_deduction @json
                                       ,22
                                       ,99999
    
        DELETE FROM #data WHERE user_serial = @userSerial AND leave_date = @applyDate
    
        SET @i += 1
      END

  	COMMIT TRANSACTION
  END TRY
  BEGIN CATCH
    DECLARE @errStr VARCHAR(MAX) = ERROR_MESSAGE();

    IF XACT_STATE() <> 0
    BEGIN
      ROLLBACK TRANSACTION;
    END;
    RAISERROR (@errStr, 16, 1);
  END CATCH;

  SET NOCOUNT OFF;
END